package cn.kuporo.seckill.order.application.event.handler;

import cn.hutool.core.util.StrUtil;
import cn.kuporo.seckill.common.constants.MQConstants;
import cn.kuporo.seckill.order.domain.event.SeckillOrderEvent;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component; /**
 * @author: kuporo
 * @since: 2025/7/9
 * @description:
 */
@Component
@ConditionalOnProperty(name = "event.publish.type", havingValue = "rocketmq")
@RocketMQMessageListener(consumerGroup = MQConstants.EVENT_ORDER_CONSUMER_GROUP, topic = MQConstants.TOPIC_EVENT_ROCKETMQ_ORDER)
@Slf4j
@RequiredArgsConstructor
public class SeckillOrderRocketMQEventHandler implements RocketMQListener<String> {
    @Override
    public void onMessage(String message) {
        if (StrUtil.isEmpty(message)){
            log.info("rocketmq|orderEvent|接收订单事件为空");
            return;
        }
        SeckillOrderEvent seckillOrderEvent = this.getEventMessage(message);
        if (seckillOrderEvent.getId() == null){
            log.info("rocketmq|orderEvent|订单参数错误");
        }
        log.info("rocketmq|orderEvent|接收订单事件|{}", JSON.toJSON(seckillOrderEvent));
    }

    private SeckillOrderEvent getEventMessage(String message){
        JSONObject jsonObject = JSONObject.parseObject(message);
        String eventStr = jsonObject.getString(MQConstants.MSG_KEY);
        return JSONObject.parseObject(eventStr, SeckillOrderEvent.class);
    }
}
